<?php
/**
 * Created by PhpStorm.
 * User: rain
 * Date: 2018/4/5
 * Time: 下午4:51
 */

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\UserService;
use App\User;
use App\Utils\MiniProgramUtil;
use App\Utils\OfficialAccountUtil;
use EasyWeChat\Kernel\Messages\Image;
use EasyWeChat\Kernel\Messages\Link;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Faker\Provider\Uuid;

class WechatController extends Controller
{
    private $userService;
    private $miniProgramUtil;
    private $officialAccountUtil;

    public function __construct(UserService $userService, MiniProgramUtil $miniProgramUtil, OfficialAccountUtil $officialAccountUtil)
    {
        $this->userService = $userService;
        $this->miniProgramUtil = $miniProgramUtil;
        $this->officialAccountUtil = $officialAccountUtil;
    }


    public function codeLogin(Request $request)
    {
        $rules = [
            'code' => 'required|string',
        ];

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()){
            return $this->error();
        }

        try{
            if(env('APP_ENV')=='local'){
                $user=User::first();
                if(empty($user)){
                    $user=new User();
                    $user->api_token=Uuid::uuid();
                    $user->avatar=User::DEFAULT_AVATAR;
                    $user->open_id=Uuid::uuid();
                    $user->union_id=Uuid::uuid();
                    $user->invite_code=Uuid::uuid();
                    $user->save();
                    $user=User::find($user->id);
                }
            }else{
                $user = $this->userService->codeRegister($request->code);
            }


            return $this->success(['user' => $user]);
        }catch(\Exception $e){
            return $this->error($e->getMessage());
        }

    }

    public function getAuthByCode(Request $request)
    {
        $code = $request->get('code', null);
        if (empty($code)){
            return $this->error();
        }

        try{
            $app = $this->officialAccountUtil->getApp();
            $wxUser = $app->oauth->user();
            $userInfo = $wxUser->getOriginal();
            //            $data = [
            //                'unionId' => $userInfo['unionid'],
            //                'openId' => $userInfo['openid'],
            //                'nickName' => $userInfo['nickname'],
            //                'avatarUrl' => $userInfo['headimgurl'],
            //            ];
            /** @var User $user */
            $user = User::where(['open_id' => $userInfo['openid']])->first();

            if (empty($user)){
                $user = new User();
                $user->api_token = Uuid::uuid1();
            }
            $user->open_id = $userInfo['openid'];
            $user->session_key = $userInfo['openid'];
            $user->nick_name = $userInfo['nickname'];
            $user->avatar = $userInfo['headimgurl'];
            $user->channel = 'wxd574dd94ca33b140';
            $user->save();

            return $this->success(['user' => $user]);
        }catch(\Exception $e){
            Log::info('授权信息:' , $userInfo);
            Log::info('授权失败:' . $e->getMessage());

            return $this->error('授权失败');
        }
    }

    public function wxShare(Request $request)
    {
        $url = $request->get('url');
        $offical = $this->officialAccountUtil->getApp();;
        $wxConf = $offical->jssdk->setUrl($url)->buildConfig([
            "onMenuShareAppMessage",
            'onMenuShareTimeline',
            "updateTimelineShareData",
            "updateAppMessageShareData",
        ], false, false, false);

        return $this->success(['wxconfig' => $wxConf,]);
    }




    public function wxLogin(Request $request)
    {
        $rules = [
            'code' => 'required|string',
            'encrypted_data' => 'required|string',
            'iv' => 'required|string',
        ];

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()){
            return $this->error();
        }

        try{
            $user = $this->userService->wxRegister($request->code, $request->encrypted_data, $request->iv);

            return $this->success(['user' => $user]);
        }catch(\Exception $e){
            return $this->error($e->getMessage());
        }

    }


    public function message(Request $request)
    {
        if ($request->isMethod('GET')){
            return $request->get('echostr', '验证字符串');
        }

        $app = $this->miniProgramUtil->getApp();
        $app->server->push(function ($message){
            $content = trim($message['Content']);
            //$openId=$message['FromUserName'];
            if ($content == 1){
                $link = [
                    'title' => "官方福利群",
                    'description' => '“程序试玩中心”邀请你加入福利群',
                    'url' => 'http://a.gzliemao.com/c/3aa9cb8e73d1c679ae428ca3587da500',
                    'thumb_url' => 'https://image.lingyiliebian.com/static/trialplay/logo.png',
                ];

                return new Link($link);
            }elseif ($content == 2){
                //客服二维码
                return new Image($this->miniProgramUtil->getTempImageMediaId());
            }

            return "您好！欢迎关注我!";
        });

        $response = $app->server->serve();

        return $response;


    }

}
